import store from '@/store';
import {defineStore} from 'pinia';
import {ref} from 'vue';
import {useAppStore} from './app.ts';
import global from '@/utils/global.ts';
import router from '@/router/index.ts';
import {delTokenInfo} from '@/utils/token.ts';
import {resolveMenus, fetchRoute} from '@/utils/menus.ts';
import {MenuDataPro, RouteData} from '@/components/layout/index.ts';

export const useUserStore: any = defineStore(
  'user',
  () => {
    const hasInfo = ref<boolean>(false);
    const usersInfo = ref<any>({});
    const usersMenus = ref<MenuDataPro[]>([]);
    const usersRoutes = ref<RouteData[]>([]);
    const usersPermits = ref<Record<any, boolean>>({});

    const clearCache = () => {
      hasInfo.value = false;
      usersInfo.value = {};
      usersMenus.value = [];
      usersRoutes.value = [];
      usersPermits.value = {};
    };
    const setUsersInfo = (data: any) => {
      const appStore = useAppStore();
      const {menus, routes, permits, mappers} = resolveMenus(data.menus);
      // 设置菜单以及路由数据
      hasInfo.value = true;
      usersInfo.value = data;
      usersMenus.value = menus;
      usersRoutes.value = routes;
      usersPermits.value = permits;
      appStore.setMenusPaths(mappers);
    };
    const removeRoute = () => {
      fetchRoute(usersRoutes.value, route => {
        router.removeRoute(route.name);
      });
    };
    const getUserId = () => {
      return usersInfo?.value?.id + '';
    };
    const logout = () => {
      const appStore = useAppStore();
      // 清除token
      delTokenInfo();
      // 清除缓存
      clearCache();
      // 清理路由
      removeRoute();
      // 清理app的缓存
      appStore.clearCache();
      // 跳转到登录页
      router.push({path: global.loginPage.path});
    };

    return {
      hasInfo: hasInfo,
      usersInfo: usersInfo,
      usersMenus: usersMenus,
      usersRoutes: usersRoutes,
      usersPermits: usersPermits,
      getUserId: getUserId,
      clearCache: clearCache,
      setUsersInfo: setUsersInfo,
      logout: logout
    };
  },
  {
    persist: {
      key: 'user',
      paths: ['usersInfo']
    }
  }
);

// 在组件setup函数外使用
export function userStoreOutside() {
  return useUserStore(store);
}
